/**
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import BaseModel from '../../../../../../../common/utils/src/main/ets/default/model/BaseModel';
import LogUtil from '../../../../../../../common/utils/src/main/ets/default/baseUtil/LogUtil';
import CertManager from '@ohos.security.certManager';

const MODULE_TAG: string = 'setting_vpn:VPNCertModel:';

export class Credential {
  alias: string;
  certUri: string;
  keyNum: number;
}
/**
 *  Cert class
 */
class VpnCertModel extends BaseModel {
  certAlias:string[] = [];

  init(){
    this.getPrivateCredList((error: number, result: Credential[]) => {
      try {
        if (!error) {
          this.certAlias = result.map((cer: Credential) => {
            return cer.alias;
          })
          LogUtil.info(MODULE_TAG + `cert = ${JSON.stringify(this.certAlias)}`);
        }
      } catch (error) {
        LogUtil.info(MODULE_TAG + JSON.stringify(error));
      }
    })
  }

  /**
   * get the vpn cer list
   * @param callback
   * @returns
   */
  public async getPrivateCredList(callback: Function): Promise<void> {
    LogUtil.info(MODULE_TAG + `getPrivateCredList start`);
    let result: Credential[] = [];
    try {
      // @ts-ignore
      let certificateList = await CertManager.getPrivateCertificateList();
      if(certificateList && certificateList.credentialList) {
        for (let i = 0; i < certificateList.credentialList.length; i++) {

          let credential = certificateList.credentialList[i];

          let alias = credential.alias;
          let certUri = credential.keyUri;
          let cer = await CertManager.getPrivateCertificate(String(certUri));
          let keyNum = cer.credential.keyNum; // 证书个数
          result.push({ alias: alias, certUri: certUri, keyNum: keyNum })
        }
      }
      LogUtil.info(MODULE_TAG + `getPrivateCredList size =  ${JSON.stringify(result.length)}`);
      callback(undefined, result);
    } catch (err) {
      callback(-1, err);
      LogUtil.error(MODULE_TAG + `getPrivateCredList error ${JSON.stringify(err)}`);
    }
  }
}

let vpnCertModel = new VpnCertModel();
export default vpnCertModel;